package com.enjoyor.soa.traffic.util.pinyin;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinYinUtils {

	public static String getPinYinAbbr(String chineseStr) {
		String abbr = "";
		try {
			if(null != chineseStr)
			{
				for (int i = 0; i < chineseStr.length(); i++) {
					if (isChinese(chineseStr.charAt(i))) 
					{
						String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(chineseStr.charAt(i));
						abbr = abbr + pinyin[0].toUpperCase().charAt(0);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return abbr;
	}

	public static Boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}
	
	 /**
	     * 将字符串中的中文转化为大写拼音缩写,其他字符不变
	     * 2016/7/1
	     * @author WL
	     */
	    public static String getPingYin(String inputString) {
	    	String regEx = "[\u4e00-\u9fa5]";
	    	Pattern pat = Pattern.compile(regEx);
	    	Matcher matcher = pat.matcher(inputString);
	    	if (!matcher.find()){
	    		return inputString;
	    	}
	        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
	        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
	        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
	        format.setVCharType(HanyuPinyinVCharType.WITH_V);
	        char[] input = inputString.trim().toCharArray();
	        String output = "";
	        try {
	            for (char curchar : input) {
	                if (java.lang.Character.toString(curchar).matches(
	                        "[\\u4E00-\\u9FA5]+")) {
	                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(
	                            curchar, format);
	                    output += temp[0].toUpperCase().charAt(0);
	                } else
	                    output += java.lang.Character.toString(curchar);
	            }
	        } catch (BadHanyuPinyinOutputFormatCombination e) {
	            e.printStackTrace();
	        }
	        return output;
	    }

}
